package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LingkeGateway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(LingkeGateway.class);

    private static final String SUCCESS = "0";

    private static final String FORMAT_DATE = "yyyyMMddHHmmss";

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = null;
        try {
            String[] phone = entity.getPhone().split(",");
            SimpleDateFormat format = new SimpleDateFormat(FORMAT_DATE);
            String ts = format.format(new Date());
            String password = MD5Util.encode(info.getAccount() + info.getPassword() + ts).toLowerCase();
            Map paramMap = new HashMap();
            paramMap.put("username", info.getAccount());
            paramMap.put("ts", ts);
            paramMap.put("pwd", password);
            paramMap.put("mobile", entity.getPhone());
            paramMap.put("content", entity.getContent());
            logger.info("LingkeGateway send params：{},", paramMap);
            String response = doPost(info.getServerAddr(), paramMap);
            logger.info("LingkeGateway send result：{},", response);
            Map<String, Object> resMap = JSON.parseObject(response, Map.class);
            if (resMap != null && SUCCESS.equals(resMap.get("code") + "")) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
                result = (String) resMap.get("taskid");
            } else {
                result = resMap.get("code") + "" == null ? "网关请求超时" : resMap.get("code") + ":" + resMap.get("msg");
            }
        } catch (Exception e) {
            logger.error("LingkeGateway send error ! ", e);
            result = "";
        } finally {
            handlerResponse(entity, result, status);
        }
    }

    @Override
    public int queryBalance() {
        try {
            SimpleDateFormat format = new SimpleDateFormat(FORMAT_DATE);
            String ts = format.format(new Date());
            String password = MD5Util.encode(info.getAccount() + info.getPassword() + ts).toLowerCase();
            Map paramMap = new HashMap();
            paramMap.put("username", info.getAccount());
            paramMap.put("ts", ts);
            paramMap.put("pwd", password);
            logger.info("LingkeGateway queryBalance param {}", paramMap);
            String response = doPost(info.getServerAddr().replace("httpBatchSend", "queryBalance"), paramMap);
            logger.info("{}余额查询结果:{}", info.getName(), response);
            JSONObject res = JSON.parseObject(response);
            if (SUCCESS.equals(res.getString("code"))) {
                return res.getInteger("msg");
            } else {
                logger.error("LingkeGateway queryBalance response error : {}{}", res.getString("code"), res.getString("msg"));
            }
        } catch (Exception e) {
            logger.error("LingkeGateway queryBalance error ! ", e);
        }
        return 0;
    }

    //主动查询获取报告状态
    public boolean queryStatus() {
        try {
            SimpleDateFormat format = new SimpleDateFormat(FORMAT_DATE);
            String ts = format.format(new Date());
            String password = MD5Util.encode(info.getAccount() + info.getPassword() + ts).toLowerCase();
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("username", info.getAccount());
            paramMap.put("pwd", password);
            paramMap.put("ts", ts);
            String url = info.getServerAddr().replace("httpBatchSend", "queryReport");
            logger.info("LingkeGateway queryStatus HttpClientUtil.doPost URL : {}", url);
            String jsonStr = doPost(url, paramMap);
            logger.info("LingkeGateway queryStatus return Result : {}", jsonStr);
            Map<String, Object> resMap = JSON.parseObject(jsonStr, Map.class);
            String code = resMap.get("code") + "";
            List<Map<String, Object>> report = (List<Map<String, Object>>) resMap.get("report");
            if (report != null && SUCCESS.equals(code)) {
                for (Map<String, Object> map : report) {
                    int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
                    String messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, map.get("smsid") + "" + map.get("mobile"));
                    JedisService.hdel(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, map.get("smsid") + "" + map.get("mobile"));
                    String result = map.get("gwcode") + "";
                    if ("DELIVRD".equals(result)) {
                        status = SmsMsgStatusEnum.SEND_SUCCESS.index;
                    }
                    if (StringUtils.isBlank(messageId)) {
                        logger.warn("LingkeGateway queryStatus messageId is null params : {}", resMap);
                    }
                    receiveReport(status, messageId, result);
                }
            }
        } catch (Exception e) {
            logger.error("LingkeGateway queryStatus error ! ", e);
        }
        return false;
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        return false;
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return false;
    }

    @Override
    public boolean queryReceiveMsg() {
        return false;
    }


}
